//
//  LoginV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/7.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "LoginV2ViewController.h"

#import "XYViewController.h"
#import "RegistV2ViewController.h"
#import "ForgetPwdViewController.h"
#import "PersonCertV2ViewController.h"

@interface LoginV2ViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) LoginV2ViewModel* viewModel;

// UI
//@property (weak, nonatomic) UILabel *addressLabel;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIButton* closeBtn;
@property (weak, nonatomic) IBOutlet UIButton* registBtn;
@property (weak, nonatomic) IBOutlet UIView* phonePwdLoginView;
@property (weak, nonatomic) IBOutlet UIView* phoneVerCodeLoginView;
@property (weak, nonatomic) IBOutlet UIButton* thirdLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton* xyBtn;

@end

@implementation LoginV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* willDisAppearSignal = [[self rac_signalForSelector:@selector(viewWillDisappear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }];
    
    [willDisAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:[willAppearSignal replay]] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RACSignal* changeTypeSignal = [RACObserve(self.viewModel, type) distinctUntilChanged];
    
    RAC(self.phonePwdLoginView, hidden) = [[changeTypeSignal replay] map:^id(id value) {
        
        NSInteger curType = [value integerValue];
        
        return @(curType != 0);
    }];
    
    RAC(self.phoneVerCodeLoginView, hidden) = [[changeTypeSignal replay] map:^id(id value) {
        
        NSInteger curType = [value integerValue];
        
        return @(curType != 1);
    }];
    
    [[self.closeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        [self _close];
    }];
    
    [[self.registBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        [self _push2RegistVC];
    }];
    
    [[self.thirdLoginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        [DataManager sharedDataManager].isInThirdLogin = YES;
        
        [self.view endEditing:YES];
        [MBProgressHUD mh_showProgressHUD:@"微信授权登陆中..."];
        
        [self.viewModel.wxCommand execute:nil];
    }];
    
    self.xyBtn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self)
        
        [self _pushXYVC];
        
        return [RACSignal empty];
    }];
    
    // 验证码
    /// 数据成功
    [[self.viewModel.verCodeCommand.executionSignals.switchToLatest deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self);
         [MBProgressHUD mh_hideHUD];
         
         [MBProgressHUD mh_showTips:x];
     }];
    
    /// 错误信息
    [self.viewModel.verCodeCommand.errors subscribeNext:^(NSError *error) {
        /// 处理验证错误的error
        if ([error.domain isEqualToString:SUCommandErrorDomain]) {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return ;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
    
    // 登录按钮
    /// 数据成功
    [[[self.viewModel.loginCommand.executionSignals.switchToLatest merge:self.viewModel.wxCommand.executionSignals.switchToLatest] deliverOnMainThread]
     subscribeNext:^(id x)
    {
        @strongify(self);
        [MBProgressHUD mh_hideHUD];
        
        if ([DataManager sharedDataManager].isInThirdLogin)
        {
            UserInfoData* userInfoData = x;
            
            if (userInfoData.mobile && [userInfoData.mobile isNotBlank])
            {
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }
            else
            {
                // 跳转个人认证
                [self _push2PersonCertVC];
            }
        }
        else
        {
            [MBProgressHUD mh_showTips:x];
            
            UserManagerV2* uMgr = [UserManagerV2 sharedUserManagerV2];
            
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
        
        [DataManager sharedDataManager].isInThirdLogin = NO;
     }];
    
    /// 错误信息
    [[self.viewModel.loginCommand.errors merge:self.viewModel.wxCommand.errors] subscribeNext:^(NSError *error)
     {

        [DataManager sharedDataManager].isInThirdLogin = NO;
        
        [MBProgressHUD mh_hideHUD];
        
        /// 处理验证错误的error
        if ([error.domain isEqualToString:SUCommandErrorDomain]) {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return ;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
}

- (void)_setupAllView
{
    @weakify(self);
    
    {
        UIView* inputView = [self.phonePwdLoginView viewWithTag:10];
        UIView* text1View = [inputView viewWithTag:100];
        UITextField* phoneTF = [text1View viewWithTag:1000];
        UIView* text2View = [inputView viewWithTag:101];
        UITextField* pwdTF = [text2View viewWithTag:1010];
        UIButton* forgetBtn = [self.phonePwdLoginView viewWithTag:11];
        UIButton* loginBtn = [self.phonePwdLoginView viewWithTag:12];
        UIButton* vercodeSwitchBtn = [self.phonePwdLoginView viewWithTag:13];
        
        RAC(self.viewModel, strPwdLoginPhone) = [[phoneTF rac_textSignal] distinctUntilChanged];
        RAC(self.viewModel, strPwd) = [[pwdTF rac_textSignal] distinctUntilChanged];
        
        [[forgetBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            
            [self _push2ForgetVC];
        }];
        [[loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            
            [self _login];
        }];
        [[vercodeSwitchBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            @strongify(self);
            
            self.viewModel.type = 1;
        }];
    }
    
    {
        UIView* input2View = [self.phoneVerCodeLoginView viewWithTag:10];
        UIView* text1View = [input2View viewWithTag:100];
        UITextField* phoneTF = [text1View viewWithTag:1000];
        UIView* text2View = [input2View viewWithTag:101];
        UITextField* vercodeTF = [text2View viewWithTag:1010];
        UIButton* vercodeBtn = [text2View viewWithTag:1011];
        UIButton* loginBtn = [self.phoneVerCodeLoginView viewWithTag:11];
        UIButton* pwdSwitchBtn = [self.phoneVerCodeLoginView viewWithTag:12];
        
        RAC(self.viewModel, strVercodeLoginPhone) = [[phoneTF rac_textSignal] distinctUntilChanged];
        RAC(self.viewModel, strVercode) = [[vercodeTF rac_textSignal] distinctUntilChanged];
        
        DataManager* dm = [DataManager sharedDataManager];
        [[[RACObserve(dm.phoneVCodeCaler, verCodeTime) deliverOnMainThread] map:^id(id value) {
            @strongify(self)
            
            int waitTime = [value intValue];
            
            if (waitTime > 0)
            {
                vercodeBtn.userInteractionEnabled = NO;
                
                return [NSString stringWithFormat:@"%ds", waitTime];
            }
            else
            {
                vercodeBtn.userInteractionEnabled = YES;
                
                return @"获取验证码";
            }
        }] subscribeNext:^(id x) {
            @strongify(self)
            
            NSString* str = x;
            
            vercodeBtn.titleLabel.text = str;
            
            [vercodeBtn setTitle:str forState:UIControlStateNormal];
        }];
        
        [[[[vercodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] deliverOnMainThread]
          doNext:^(id x) {
              @strongify(self);
              [self.view endEditing:YES];
              [MBProgressHUD mh_showProgressHUD:[NSString stringWithFormat:@"%@....", @"获取验证码"]];
          }]
         subscribeNext:^(UIButton *sender) {
             @strongify(self);
             [self.viewModel.verCodeCommand execute:nil];
         }];
        
        [[loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            
            [self _login];
        }];
        
        [[pwdSwitchBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            
            self.viewModel.type = 0;
        }];
    }
}

#pragma mark - 功能
- (void)_login
{
    [self.view endEditing:YES];
    
    [MBProgressHUD mh_showProgressHUD:@"登陆中..."];
    
    [self.viewModel.loginCommand execute:nil];
}

#pragma mark - 跳转
- (void)_close
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Tabbar_Select object:@0];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)_push2PersonCertVC
{
    PersonCertV2ViewModel* vm = [[PersonCertV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"个人认证"}];
    vm.isBack2Dismiss = YES;
    PersonCertV2ViewController* vc = [[PersonCertV2ViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2RegistVC
{
    RegistV2ViewModel* vm = [[RegistV2ViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"新用户注册"}];
    RegistV2ViewController* vc = [[RegistV2ViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2ForgetVC
{
    ForgetPwdViewModel* vm = [[ForgetPwdViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"修改密码"}];
    ForgetPwdViewController* vc = [[ForgetPwdViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_pushXYVC
{
    XYViewModel* vm = [[XYViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"用户协议"}];
    XYViewController* vc = [[XYViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
